package com.study.storm.storm.bolt;


import com.study.storm.entity.User;
import com.study.storm.service.UserService;
import com.study.storm.utils.GetSpringBean;
import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.topology.base.BaseRichBolt;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Tuple;

import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

/**
 * @author
 */
public class YearBolt extends BaseRichBolt{

    /**
     *
     */
    private static final long serialVersionUID = 6542256546124282695L;

    @Override
    public void prepare(Map map, TopologyContext arg1, OutputCollector collector) {
        UserService userService = GetSpringBean.getBean(UserService.class);
    }


    @Override
    public void execute(Tuple tuple) {
        User user = (User) tuple.getValueByField("user");
        if(Objects.isNull(user)){
            return;
        }
        LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(new Random().nextInt(5)));
        user.setUserName("yearn");
        System.out.println("YEAR Time：" + System.currentTimeMillis()+ "--" + "user:" + user);
    }

    /**
     * cleanup是IBolt接口中定义,用于释放bolt占用的资源。
     * Storm在终止一个bolt之前会调用这个方法。
     */
    @Override
    public void cleanup() {
        System.out.println("YEAR cleanup");
    }

    @Override
    public void declareOutputFields(OutputFieldsDeclarer arg0) {
        arg0.declare(new Fields("user"));
    }


}